package com.shortchainsystem.util;

import com.shortchainsystem.model.domain.link.LinkStats;
import com.shortchainsystem.model.exception.CustomCodeEnum;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class LinkUtil {
    private static final String BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    /**
     *    生成短链
     * @param id
     * @return
     */
    public static String idToShortKey(String id) {
        StringBuilder stringBuilder = new StringBuilder();
        Long longKey = Long.valueOf(id);
        while (longKey > 0) {
            stringBuilder.append(BASE62.charAt((int) (longKey % 62)));
            longKey = longKey / 62;
        }

        while (stringBuilder.length() < 6) {
            stringBuilder.append(0);
        }

        return stringBuilder.reverse().toString();
    }

    /**
     *    验证短链是否有效
     * @param shortKey
     * @return
     */
    public static String shortKeyToId(String shortKey) {
        long id = 0;
        for (int i = 0; i < shortKey.length(); i++) {
            id = id * 62 + BASE62.indexOf(shortKey.charAt(i));
        }

        return String.format("%010d",id);
    }

    // TODO 获取操作系统、浏览器、IP地址、IP归属地、访问设备等信息
    public static LinkStats getAccessInfo(HttpServletRequest request) throws JSONException, IOException {
        LinkStats linkStats = new LinkStats();
        // 获取用户代理字符串，并且获取操作系统和浏览器信息
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        linkStats.setOs(userAgent.getOperatingSystem().getName());
        linkStats.setBrowser(userAgent.getBrowser().getName());
        // 获取客户端IP信息
        getClientIp(linkStats);
        // 获取当前设备
        linkStats.setDevice(getDevice(request));
        return linkStats;
    }

    // 获取客户端IP信息
    private static void getClientIp(LinkStats linkStats) throws IOException, JSONException {
        URL url = new URL(IP_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        connection.disconnect();

        // 使用正则表达式提取JSON字符串（注意：这种方法不是很健壮）
        String jsonString = content.toString().replaceAll(".*IPCallBack\\((.*)\\);.*", "$1");

        // 解析JSON对象
        JSONObject jsonObject = new JSONObject(jsonString);
        linkStats.setIpAddress(jsonObject.getString("ip"));
        linkStats.setIpLocation(jsonObject.getString("addr"));
    }

    // 获取当前访问设备
    public static String getDevice(HttpServletRequest request){
        // 获取User-Agent信息
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) {
            return "未知设备";
        }
        // 检查是否为移动设备
        if (userAgent.toLowerCase().contains("mobile") || userAgent.toLowerCase().contains("android")) {
            return "手机";
        }
        // 检查是否为平板设备
        if (userAgent.toLowerCase().contains("tablet") || userAgent.toLowerCase().contains("ipad")) {
            return "平板电脑";
        }
        // 默认为桌面设备
        return "笔记本电脑/台式机";
    }

    // 判断该链接是否可正常访问
    public static boolean checkUrl(String url) {
        try {
            URL urlObj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            int responseCode = conn.getResponseCode();
            return responseCode == 200;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println(LinkUtil.shortKeyToId("0R9sQD"));
    }
}
